<template>
  <div class="app-container" >
    <div class="filter-container">
      <el-button type="primary" @click="handleReturn" icon="el-icon-s-promotion">返回分类</el-button>
      <el-button type="success" @click="handleAdd" icon="el-icon-edit">添加</el-button>
      <el-button type="primary" @click="checkAll" icon="el-icon-refresh">{{chooseTitle}}</el-button>
      <el-button type="danger" @click="handleDeleteBatch" icon="el-icon-delete">删除选中</el-button>
      <el-button type="success" @click="setCover" icon="el-icon-video-camera-solid">设为封面</el-button>
    </div>

    <el-row :gutter="20" v-loading="Loading">
      <el-col :span="4" v-for="(picture, index) in pictureDatas" :key="picture.uid" style="margin-bottom: 20px;">
        <div class="grid-content bg-purple">
          <el-card :body-style="{ padding: '0px', textAlign: 'center' }" shadow="always">
            <input style="position: absolute;z-index: 100;zoom:130%" type="checkbox" :id="picture.uid" :checked="pictureUids.indexOf(picture.uid)>=0" @click="checked(picture)" />
            <el-image :src="VUE_APP_IMAGE_URL + picture.pictureUrl" style="cursor:pointer" fit="cover" :preview-src-list="[VUE_APP_IMAGE_URL + picture.pictureUrl]" @click="showPicture(picture.pictureUrl)" />
            <div>
              <span class="media-title" v-if="picture.picName">{{picture.picName}}</span>
              <span class="media-title" v-else>图片 {{index + 1}}</span>
            </div>
            <div style="margin-bottom: 14px;">
              <el-button-group>
                <el-tooltip class="item" effect="dark" content="复制图片地址" placement="bottom-start" style="margin-right: 2px">
                  <el-button size="mini" icon="el-icon-copy-document" @click="copyUrl(VUE_APP_IMAGE_URL + picture.pictureUrl)" />
                </el-tooltip>

                <el-tooltip class="item" effect="dark" content="复制Markdown格式图片地址" placement="bottom-start" style="margin-right: 2px">
                  <el-button type="primary" size="mini" icon="el-icon-document-copy" @click="copyMarkdownUrl(VUE_APP_IMAGE_URL + picture.pictureUrl, VUE_APP_IMAGE_URL + picture.pictureUrl)"></el-button>
                </el-tooltip>

                <!-- <el-tooltip class="item" effect="dark" content="裁剪图片" placement="bottom-start" style="margin-right: 2px">
                  <el-button type="warning" size="mini" icon="el-icon-s-open" @click="handleCropper(picture)" />
                </el-tooltip> -->

                <el-tooltip class="item" effect="dark" content="删除图片" placement="bottom-start" style="margin-right: 2px">
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(picture)" />
                </el-tooltip>
              </el-button-group>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <!--分页-->
    <div class="block">
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" center :visible.sync="dialogFormVisible" :close-on-click-modal='false' :before-close="handleClose" width="600px">
      <el-upload drag name="multipartFile" :before-upload="beforeUpload" :action="uploadPictureHost" :data="otherData" :on-success="fileSuccess" :on-error="fileError" multiple :show-file-list="false">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">只能上传图片，且不超过10MB</div>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import { getPictureList, addPicture, deleteBatch } from "@/api/picture";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      Loading: true,
      VUE_APP_IMAGE_URL: process.env.VUE_APP_IMAGE_URL,
      pictureSortUid: "", //相册类别页传递过来的uid
      keyword: "",
      pictureDatas: [],
      pictureUids: [], //选中的图片uid
      uploadPictureHost: null, //文件上传地址
      currentPage: 1,
      pageSize: 24,
      total: null,
      title: "上传图片",
      dialogFormVisible: false,
      chooseTitle: "全部选中",
      isCheckedAll: false, //是否全选
      otherData: {
        userUid: this.$store.getters.userUid,  //上传人
        projectName: "kebol",
        sortName: "admin",
        // token: getToken()
      },
    };
  },
  created() {
    //传递过来的pictureSordUid
    this.pictureSortUid = this.$route.query.pictureSortUid; //获取相册类别页传递过来的uid
    // TODO 获取图片列表
    // this.pictureList();
    //图片上传地址
    this.uploadPictureHost = process.env.VUE_APP_ADMIN_API + "/upload";
  },
  methods: {
    pictureList() {
      //防止没有分类id的情况下直接进入图片列表
      if( !this.pictureSortUid){
        this.$router.replace("/picture")
      }
      var params = {};
      params.keyword = this.keyword;
      params.pictureSortUid = this.pictureSortUid;
      params.pageSize = this.pageSize;
      params.currentPage = this.currentPage;
      this.Loading = true;
      getPictureList(params).then(response => {
        this.pictureDatas = response.data.records;
        this.currentPage = response.data.current;
        this.pageSize = response.data.size;
        this.total = response.data.total;
        this.Loading = false;
      });
    },
    handleAdd() {
      this.dialogFormVisible = true;
    },
    fileSuccess(response, file, fileList) {
      if (file.status == "success") {
        let picture = {};
        picture.fileUid = response.uid;
        picture.pictureSortUid = this.pictureSortUid;
        picture.picName = response.picName;
        this.$store.dispatch('app/setLoading', true);
        addPicture(picture).then(response => {
          this.pictureList();
          this.$message({
            type: "success",
            message: response.data
          });
        });
      } else {
        this.$message({
          type: "error",
          message: response.data
        });
      }
    },
    fileError(response, file, fileList) {
      this.$message({
        type: "error",
        message: "上传失败"
      });
    },
    //限制文件上传类型及大小，图片压缩处理，main.js中引入的组件
    beforeUpload(file) {
      this.$store.dispatch('app/setLoading', true);
      return this.$elUploadBeforeUpload(file);
    },
    handleReturn() {
      this.$router.push({
        path: "pictureSort"
      });
    },
    checked(data) {
      //选中图片
      let index = this.pictureUids.indexOf(data.uid);
      if (index == -1) {
        this.pictureUids.push(data.uid);
      } else {
        this.pictureUids.splice(index, 1); //删除
      }
    },
    checkAll() {
      //如果是全选
      if (this.isCheckedAll) {
        this.pictureUids = [];
        this.isCheckedAll = false;
        this.chooseTitle = "全部选中";
      } else {
        this.pictureUids = [];
        this.pictureDatas.forEach(picture=>{
          this.pictureUids.push(picture.uid)
        })
        this.isCheckedAll = true;
        this.chooseTitle = "取消全选";
      }
    },
    handleDeleteBatch() {
      if (this.pictureUids.length <= 0) {
        this.$notify({
          title: "温馨提示：",
          message: "请先选中图片！",
          type: "error",
        });
        return;
      }
      this.$confirm("此操作将删除【" + this.pictureUids.length + "】张图片？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let uids = this.pictureUids.join(","); //将数组逗号拼接字符串
          this.$store.dispatch('app/setLoading', true);
          deleteBatch(uids).then(res => {
            this.$notify({
              title: "成功",
              message: res.data,
              type: "success",
            });
          }).finally(() => {
            this.$nextTick(() => {
              this.pictureUids = [];
              this.pictureList();
            });

          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    setCover() { },
    showPicture() { },
    copyUrl(url) {
      this.$commonUtil.copyText(url)
      this.$commonUtil.message.success('复制链接到剪切板成功')
    },
    copyMarkdownUrl(name, url) {
      const text = '![' + name + '](' + url + ')'
      this.$commonUtil.copyText(text)
      this.$commonUtil.message.success('复制Markdown格式链接到剪切板成功')
    },
    handleCropper(picture) { },
    handleDelete(picture) {
      this.pictureUids = [picture.uid]
      this.handleDeleteBatch()
    },
    //改变页码
    handleCurrentChange(val) {
      this.currentPage = val; //改变当前所指向的页数
      this.pictureList();
    },
    handleClose(done) {
      done();
    }
  }
};
</script>

<style lang="scss">
.el-row {
  &:last-child {
    margin-bottom: 0;
  }
}
// .el-col {
//   margin-bottom: 20px;
// }
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.el-image {
  width: 100%;
  height: 160px;
}
.media-title {
  color: #8492a6;
  font-size: 14px;
  padding: 14px;
  display: inline-block;
  white-space: nowrap;
  width: 60%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-dialog--center .el-dialog__body {
  text-align: center;
}

.el-upload-dragger {
  width: 550px;
}
</style>
